//
//  StoreViewController.m
//  CandyCrushClone
//
//  Created by Petar on 3/22/15.
//  Copyright (c) 2015 Nestorov Engineering. All rights reserved.
//

#import "StoreViewController.h"
#import "Globals.h"
#import "CommunicationManager.h"
#import "GameInfo.h"
#import "HeroInfoCell.h"
#import "PurchaseInfoCell.h"
#import "HMIAPHelper.h"
#import "UIView+Animations.h"
#import "HeroInfo.h"
#import "AudioController.h"
#import "Tracker.h"

static NSString * const HeroInfoCellIdentifier = @"HeroInfoCell";
static NSString * const PurchaseInfoCellIdentifier = @"PurchaseInfoCell";
static NSString * const RestoreCellIdentifier = @"RestoreCell";

@interface StoreViewController () <UITableViewDataSource, UITableViewDelegate, HeroInfoCellDelegate, PurchaseInfoCellDelegate, UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *chosenHeroButtonView;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIButton *heroesButton;
@property (weak, nonatomic) IBOutlet UIButton *purchasesButton;
@property (weak, nonatomic) IBOutlet UILabel *moneyLabel;

@property (weak, nonatomic) IBOutlet UIView *buyHeroPopupView;
@property (weak, nonatomic) IBOutlet UIView *upgradePopupView;
@property (weak, nonatomic) IBOutlet UIView *infoPopupView;
@property (weak, nonatomic) IBOutlet UIView *connectingPopupView;

@property (weak, nonatomic) IBOutlet UIImageView *buyingHeroImageView;
@property (weak, nonatomic) IBOutlet UILabel *buyHeroPopupPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *buyHeroPopupTextLabel;
@property (weak, nonatomic) IBOutlet UIButton *buyHeroPopupBuyButton;
@property (weak, nonatomic) IBOutlet UIButton *buyHeroPopupGetCoinsButton;

@property (weak, nonatomic) IBOutlet UILabel *upgradePopupPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *upgradePopupLevelLabel;
@property (weak, nonatomic) IBOutlet UILabel *upgradePopupTextLabel;
@property (weak, nonatomic) IBOutlet UIButton *upgradePopupUpgradeButton;
@property (weak, nonatomic) IBOutlet UIButton *upgradePopupGetCoinsButton;

@end

@implementation StoreViewController
{
    CommunicationManager *_communicationManager;
    BOOL _isShowingHeroes;
    NSArray *_purchasesModel;
    IAPProduct *_energyProduct;
    NSArray *_storePurchases;
    NSMutableArray *_heroInfoArray;
    NSArray *_upgradePrices;
    NSArray *_purchasesRewards;
    HeroInfo *_chosenHeroInfo;
    BOOL _isUpgradingAttack;
    HeroInfo *_upgradingHeroInfo;
    HeroInfo *_buyingHeroInfo;
    AudioController *_audioController;
    BOOL _isRequestingProducts;
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    UINib *heroCellNib = [UINib nibWithNibName:HeroInfoCellIdentifier bundle:nil];
    [_tableView registerNib:heroCellNib forCellReuseIdentifier:HeroInfoCellIdentifier];
    
    UINib *purchaseCellNib = [UINib nibWithNibName:PurchaseInfoCellIdentifier bundle:nil];
    [_tableView registerNib:purchaseCellNib forCellReuseIdentifier:PurchaseInfoCellIdentifier];
    
    [_tableView setContentInset:UIEdgeInsetsMake(80, 0, 17, 0)];
    
    _audioController = [AudioController sharedInstance];
    _communicationManager = [CommunicationManager sharedManager];
    [_communicationManager getAmountOfMoneyFromServer];
    
    _isRequestingProducts = NO;
    _isShowingHeroes = YES;
    _isUpgradingAttack = NO;
    _heroInfoArray = [NSMutableArray arrayWithArray:[HeroInfo getHeroInfoArray]];
    _chosenHeroInfo = [HeroInfo getChosenHeroInfo];
    
    UIImage *chosenHeroImage = [UIImage imageNamed:[NSString stringWithFormat:@"animal_%zd", _chosenHeroInfo.type]];
    [_heroesButton setBackgroundImage:chosenHeroImage forState:UIControlStateNormal];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateMoneyLabel:)
                                                 name:CMD_GET_AMOUNT_OF_MONEY
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateStoreInfo:)
                                                 name:CMD_GET_STORE_INFO
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveTransactionCompleteNotification)
                                                 name:@"transaction complete"
                                               object:nil];
    
    [_communicationManager getStoreInfoFromServer];
    
    // Sets previous requested IAP products
    [self updatePurchases];
    
    // Refresh IAP products
    [self requestInAppPurchaseProducts];
    
    [Tracker trackEvent:@"Seen Heroes" withParams:nil];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    [_backButton startWobbleAnimationAfterDuration:0.25f];
    [_purchasesButton startWobbleAnimationAfterDuration:0.5f];
    [_chosenHeroButtonView startWobbleAnimationAfterDuration:0.75f];
    
    [self setChosenHeroImage];
    
}


-(void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [_backButton stopAllAnimations];
    [_purchasesButton stopAllAnimations];
    [_chosenHeroButtonView stopAllAnimations];
    
}


- (void)setChosenHeroImage
{
    
    HeroInfo *chosenHeroInfo = [HeroInfo getChosenHeroInfo];
    UIImage *heroImage = [UIImage imageNamed:[NSString stringWithFormat:@"animal_%zd", chosenHeroInfo.type]];
    [_heroesButton setBackgroundImage:heroImage forState:UIControlStateNormal];
    
}


- (void)updateMoneyLabel:(NSNotification *)notification
{
    
    NSDictionary *userInfo = notification.userInfo;
    NSNumber *amountOfMoney = userInfo[AMOUNT_OF_MONEY];
    
    _moneyLabel.text = [NSString stringWithFormat:@"%zd", [amountOfMoney integerValue]];
    
    // Synchronize user money
    [[NSUserDefaults standardUserDefaults] setInteger:[amountOfMoney integerValue] forKey:USER_MONEY_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}


- (void)updateStoreInfo:(NSNotification *)notification
{
    
    NSDictionary *userInfo = notification.userInfo;
    
    _purchasesRewards = userInfo[STORE_PURCHASES_REWARDS];
    _upgradePrices = userInfo[STORE_UPGRADE_PRICES];
    
    [self setPurchasesRewards];
    
}


#pragma mark - TableView delegate methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if ( _isShowingHeroes == YES ) {
        
        return [_heroInfoArray count]; // Number of Heroes
        
    } else {
        
        return [_purchasesModel count] + 1; // Number of Purchases + Restore button
        
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // Show HeroCells
    if ( _isShowingHeroes == YES ) {
        
        HeroInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:HeroInfoCellIdentifier forIndexPath:indexPath];
        
        if ( [_heroInfoArray count] <= indexPath.row ) {
            return cell;
        }
        
        HeroInfo *heroInfo = _heroInfoArray[indexPath.row];
        
        [cell configureWithHeroInfo:heroInfo forIndexPath:indexPath];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    } else { // Show PurchaseCells
        
        // Last cell is for Restore button
        if ( indexPath.row == [_purchasesModel count] ) {
            
            UITableViewCell *restoreCell = [tableView dequeueReusableCellWithIdentifier:RestoreCellIdentifier forIndexPath:indexPath];
            
            [((UIButton *)[_tableView viewWithTag:1]) addTarget:self action:@selector(didPressRestoreButton) forControlEvents:UIControlEventTouchUpInside];
            
            return restoreCell;
            
        }
        
        PurchaseInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:PurchaseInfoCellIdentifier forIndexPath:indexPath];
        
        // If scrolls animals to bottom and switch to purchases indexPath.row is bigger than purchases objects
        if ( [_purchasesModel count] <= indexPath.row ) {
            
            return cell;
            
        }
        
        IAPProduct *iapProduct = _purchasesModel[indexPath.row];
        
        [cell configureWithIAPProduct:iapProduct forIndexPath:indexPath];
        cell.delegate = self;
        
        return cell;
        
    }
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ( _isShowingHeroes == YES ) {
        
        // Return HeroCell height
        return 256;
        
    } else {
        
        // Return PurchaseCell height
        return 75;
        
    }
    
}


- (void)didPressRestoreButton
{
    
    [_audioController playButtonClick];
    UIAlertView * alertView = [[UIAlertView alloc]
                               initWithTitle:@"Restore Content"
                               message:@"Would you like to check for and restore any previous purchases?"
                               delegate:self
                               cancelButtonTitle:@"Cancel"
                               otherButtonTitles:@"OK", nil];
    alertView.delegate = self;
    [alertView show];
    
}


- (void)reloadTableViewWithAnimation
{
    
    __weak StoreViewController *weakSelf = self;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        weakSelf.tableView.alpha = 0;
        
    } completion:^(BOOL finished) {
        
        [weakSelf.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
        [weakSelf.tableView reloadData];
        
        [UIView animateWithDuration:0.25 animations:^{
            
            weakSelf.tableView.alpha = 1;
            
        }];
        
    }];
    
}


- (IBAction)didPressHeroesButton:(id)sender
{
    
    [_audioController playButtonClick];
    
    if ( _isShowingHeroes == YES ) return;
    
    _isShowingHeroes = YES;
    [self reloadTableViewWithAnimation];
    [Tracker trackEvent:@"Seen Heroes" withParams:nil];
    
}


- (IBAction)didPressPurchasesButton:(id)sender
{
    
    [_audioController playButtonClick];
    
    if ( _isShowingHeroes == NO ) return;
    
    _isShowingHeroes = NO;
    [self reloadTableViewWithAnimation];
    [Tracker trackEvent:@"Seen Purchases" withParams:nil];
    
}


- (IBAction)didPressCloseConnectingPopup:(id)sender
{
    
    [_audioController playButtonClick];
    [self hidePopup:_connectingPopupView];
    
}


#pragma mark - Choose Hero

- (void)chooseHero:(NSInteger)heroInfoIndex
{
    
    // Exchange the chosen hero in _heroInfoArray
    HeroInfo *previousChosenHero = [_heroInfoArray firstObject];
    previousChosenHero.isChosen = NO;
    
    HeroInfo *newChosenHero = _heroInfoArray[heroInfoIndex];
    newChosenHero.isChosen = YES;
    
    // swap the two objects to make first object to be chosen
    [_heroInfoArray removeObject:newChosenHero];
    [_heroInfoArray insertObject:newChosenHero atIndex:0];
    [HeroInfo saveHeroInfoArray:_heroInfoArray];
    
    [self reloadTableViewWithAnimation];
    
    // Updates UserVariable for chosen hero
    [_communicationManager updateChosenHeroInfo];
    [GameInfo sharedInfo].localPlayer.hero.type = newChosenHero.type;
    
    [self setChosenHeroImage];
    
}


- (IBAction)didPressBackButton:(id)sender
{

    [_audioController playButtonClick];
    [self.navigationController popViewControllerAnimated:YES];
    
}



#pragma mark - In-App purchases

- (void)setPurchasesRewards
{
    
    if ( [_storePurchases count] != [_purchasesRewards count] ) {
        return;
    }
    
    for (int i = 0; i < [_storePurchases count]; i++) {
        IAPProduct *purchase = _storePurchases[i];
        purchase.reward = [_purchasesRewards[i] integerValue];
    }
    
}


- (void)requestInAppPurchaseProducts
{
    
    // Prevents from requesting multiple times at once
    if ( _isRequestingProducts == YES ) {
        return;
    }
    
    _isRequestingProducts = YES;
    
    [[HMIAPHelper sharedInstance] requestProductsWithCompletionHandler:^(BOOL success, NSArray *products) {
        
        _isRequestingProducts = NO;
        
        if ( success ) {
            
            [self updatePurchases];
            
        } else {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Something went wrong. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            
        }
        
    }];
    
}


- (void)updatePurchases
{
    
    _energyProduct = [[HMIAPHelper sharedInstance] getEnergyProduct];
    _storePurchases = [[HMIAPHelper sharedInstance] getStoreProducts];
    
    if ( _storePurchases == nil ) {
        
        [self requestInAppPurchaseProducts];
        
    } else {
        
        [self configurePurchasesModel];
        [self setPurchasesRewards];
        
        // Show purchase info
        if ( _isShowingHeroes == NO ) {
            [_tableView reloadData];
        }
        
    }
    
}


- (void)configurePurchasesModel
{
    
    // Do not include Energy purchase to the model, if it's already bought
    if ( [[NSUserDefaults standardUserDefaults] boolForKey:IS_PURCHASED_UNLIMITED_ENERGY_KEY] == YES ) {
        
        _purchasesModel = _storePurchases;
        
    } else {
        
        // Makes energy purchase to be first
        NSMutableArray *allProducts = [NSMutableArray arrayWithArray:_storePurchases];
        [allProducts insertObject:_energyProduct atIndex:0];
        
        _purchasesModel = allProducts;
        
    }
    
}


- (void)receiveTransactionCompleteNotification
{
    
    [self updatePurchases];
    
    [self hidePopup:_connectingPopupView];
    
    [_communicationManager performSelector:@selector(getAmountOfMoneyFromServer) withObject:nil afterDelay:1.0f];
    
}


#pragma mark - Custom cell delegate methods

- (void)didPressBuyIAPProductAtIndexPath:(NSIndexPath *)indexPath
{
    
    [_audioController playButtonClick];
    
    // _purchasesRewards is not recieved from server yet
    if ( _purchasesRewards == nil ) {
        return;
    }
    
    if ( [_purchasesModel count] <= indexPath.row ) {
        // index out of bounds
        return;
    }
    
    IAPProduct *iapProduct = _purchasesModel[indexPath.row];
    
    if ( iapProduct.allowedToPurchase == YES ) {
        
        [self showPopupView:_connectingPopupView];
        
        [[HMIAPHelper sharedInstance] buyProduct:iapProduct];
        
    } else  {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Something went wrong. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
    }
    
}


- (void)didPressBuyHeroButtonAtIndexPath:(NSIndexPath *)indexPath
{
    
    [_audioController playButtonClick];
    _buyingHeroInfo = _heroInfoArray[indexPath.row];
    
    [self showBuyHeroPopup];
    
}


- (void)didPressUpgradeProduceButtonAtIndexPath:(NSIndexPath *)indexPath
{
    
    [_audioController playButtonClick];
    _upgradingHeroInfo = _heroInfoArray[indexPath.row];
    _isUpgradingAttack = NO;
    
    [self configureUpgradePopup];
    [self showPopupView:_upgradePopupView];
    
}


- (void)didPressUpgradeAttackButtonAtIndexPath:(NSIndexPath *)indexPath
{
    
    [_audioController playButtonClick];
    _upgradingHeroInfo = _heroInfoArray[indexPath.row];
    _isUpgradingAttack = YES;
    
    [self configureUpgradePopup];
    [self showPopupView:_upgradePopupView];
    
}


- (void)didPressHeroButtonAtIndexPath:(NSIndexPath *)indexPath
{
    
    [_audioController playButtonClick];
    [self chooseHero:indexPath.row];
    
}


- (void)didPressInfoButton
{
    
    [_audioController playButtonClick];
    [self showPopupView:_infoPopupView];
    
}


#pragma mark - Popup methods

- (void)showPopupView:(UIView *)popupView
{
    
    popupView.superview.hidden = NO;
    popupView.superview.alpha = 0;
    
    [UIView animateWithDuration:0.5f animations:^{
        
        popupView.superview.alpha = 1;
        
    }];
    
}


- (void)hidePopup:(UIView *)popupView
{
    
    // Hide upgradePopupView
    if ( popupView.superview.isHidden == NO ) {
        
        [UIView animateWithDuration:0.5f animations:^{
            
            popupView.superview.alpha = 0;
            
        } completion:^(BOOL finished) {
            
            popupView.superview.hidden = YES;
            
        }];
        
    }
    
}


- (void)showBuyHeroPopup
{
    
    UIImage *heroImage = [UIImage imageNamed:[NSString stringWithFormat:@"animal_%zd", _buyingHeroInfo.type]];
    _buyingHeroImageView.image = heroImage;
    _buyHeroPopupPriceLabel.text = [NSString stringWithFormat:@"%zd", _buyingHeroInfo.price];
    
    NSString *popupText = [NSString stringWithFormat:@"Do you want to buy '%@' ?", _buyingHeroInfo.name];
    _buyHeroPopupTextLabel.text = popupText;
    
    BOOL hasEnoughMoney = [self hasEnoughMoneyForHeroInfo:_buyingHeroInfo];
    
    if ( hasEnoughMoney == YES ) {
        
        [self showButton:_buyHeroPopupBuyButton];
        [self hideButton:_buyHeroPopupGetCoinsButton];
        
    } else {
        
        [self showButton:_buyHeroPopupGetCoinsButton];
        [self hideButton:_buyHeroPopupBuyButton];
        
    }
    
    [self showPopupView:_buyHeroPopupView];
    
}


- (IBAction)didPressCancelPopupButton:(id)sender
{
    
    [_audioController playButtonClick];
    [self hidePopup:_buyHeroPopupView];
    [self hidePopup:_upgradePopupView];
    
}


- (IBAction)didPressGetCoinsButton:(id)sender
{
    
    [_audioController playButtonClick];
    [self didPressPurchasesButton:nil];
    [self didPressCancelPopupButton:nil];
    
}


- (IBAction)didPressBuyHeroPopupButton:(id)sender
{
    
    // Set _buyingHeroInfo to be owned and make it second in _heroInfoArray
    NSInteger buyedHeroIndex = 1;
    _buyingHeroInfo.isOwned = YES;
    [_heroInfoArray removeObject:_buyingHeroInfo];
    [_heroInfoArray insertObject:_buyingHeroInfo atIndex:buyedHeroIndex];
    
    // Make buyed hero to be chosen
    [self chooseHero:buyedHeroIndex];
    
    [self decreaseUserMoney:_buyingHeroInfo.price];
    [self hidePopup:_buyHeroPopupView];
    
    [[AudioController sharedInstance] playEffect:kBuyHeroSound];
    
}


- (void)configureUpgradePopup
{
    
    NSString *upgradeText;
    NSString *levelText;
    
    if ( _isUpgradingAttack == YES ) {
        
        upgradeText = [NSString stringWithFormat:@"Do you want to increase 'Attack' of '%@' to Level: %zd ?", _upgradingHeroInfo.name, ABS(_upgradingHeroInfo.attack) + 1];
        levelText = [NSString stringWithFormat:@"%zd x", ABS(_upgradingHeroInfo.attack) + 1];
        
    } else {
        
        upgradeText = [NSString stringWithFormat:@"Do you want to increase 'Produces' of '%@' to Level: %zd ?", _upgradingHeroInfo.name, _upgradingHeroInfo.produces + 1];
        levelText = [NSString stringWithFormat:@"%zd x", _upgradingHeroInfo.produces + 1];
        
    }
    
    _upgradePopupTextLabel.text = upgradeText;
    _upgradePopupPriceLabel.text = [NSString stringWithFormat:@"%zd", [self getNextUpgradePrice]];
    _upgradePopupLevelLabel.text = levelText;
    
    BOOL hasEnoughMoney = [self hasEnoughMoneyForUpgrade];
    
    if ( hasEnoughMoney == YES ) {
        
        [self showButton:_upgradePopupUpgradeButton];
        [self hideButton:_upgradePopupGetCoinsButton];
        
    } else {
        
        [self showButton:_upgradePopupGetCoinsButton];
        [self hideButton:_upgradePopupUpgradeButton];
        
    }
    
}


- (IBAction)didPressUpgradePopupButton:(id)sender
{
    
    // _upgradePrices is not recieved from server yet
    if ( _upgradePrices == nil ) {
        return;
    }
    
    NSInteger upgradeType;
    NSInteger upgradeLevel;
    
    // Determines of what kind is the upgrade
    if ( _isUpgradingAttack == YES ) {
        
        _upgradingHeroInfo.attack -= 1;
        upgradeType = UPGRADE_ATTACK_TYPE;
        upgradeLevel = ABS(_upgradingHeroInfo.attack);
        
    } else {
        
        _upgradingHeroInfo.produces += 1;
        upgradeType = UPGRADE_PRODUCES_TYPE;
        upgradeLevel = _upgradingHeroInfo.produces;
        
    }
    
    [HeroInfo saveHeroInfoArray:_heroInfoArray];
    
    // Upgrades hero on server
    [_communicationManager sendUpgradeRequestForHero:_upgradingHeroInfo.type andUpgrade:upgradeType];
    [_communicationManager updateChosenHeroInfo];
    
    NSInteger upgradePrice = [_upgradePrices[upgradeLevel] integerValue];
    
    [Tracker trackEvent:@"Upgrade" withParams:@{
                                                @"Hero type" : @(_upgradingHeroInfo.type),
                                                @"Type" : upgradeType == UPGRADE_ATTACK_TYPE ? @"Attack" : @"Produce",
                                                @"Price" : @(upgradePrice),
                                                @"Level" : @(upgradeLevel),
                                                }];
    
    [self decreaseUserMoney:upgradePrice];
    [self reloadTableViewWithAnimation];
    [self didPressCancelPopupButton:sender];
    
    [[AudioController sharedInstance] playEffect:kUpgradeSound];
    
}


- (IBAction)didPressCloseInfoPopupButton:(id)sender
{
    
    [_audioController playButtonClick];
    [self hidePopup:_infoPopupView];
    
}


#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    
    if ( buttonIndex == alertView.firstOtherButtonIndex ) {
        
        [self showPopupView:_connectingPopupView];
        [[HMIAPHelper sharedInstance] restoreCompletedTransactions];
        
    }
    
}


#pragma mark - Helper methods

- (BOOL)hasEnoughMoneyForHeroInfo:(HeroInfo *)heroInfo
{
    
    BOOL hasEnoughMoney = NO;
    
    NSInteger userMoney = [[NSUserDefaults standardUserDefaults] integerForKey:USER_MONEY_KEY];
    
    if ( userMoney >= heroInfo.price ) {
        hasEnoughMoney = YES;
    }
    
    return hasEnoughMoney;
    
}


- (BOOL)hasEnoughMoneyForUpgrade
{
    
    BOOL hasEnoughMoney = NO;
    
    NSInteger userMoney = [[NSUserDefaults standardUserDefaults] integerForKey:USER_MONEY_KEY];
    NSInteger nextUpgradePrice = [self getNextUpgradePrice];
    
    if ( userMoney >= nextUpgradePrice ) {
        hasEnoughMoney = YES;
    }
    
    return hasEnoughMoney;
    
}


- (NSInteger)getNextUpgradePrice
{
    
    NSInteger currentHeroUpgradeLevel;
    
    if ( _isUpgradingAttack == YES ) {
        
        currentHeroUpgradeLevel =  ABS(_upgradingHeroInfo.attack);
        
    } else {
        
        currentHeroUpgradeLevel = _upgradingHeroInfo.produces;
        
    }
    
    // If there is some problem return some relevant value
    if ( [_upgradePrices count] <= currentHeroUpgradeLevel + 1) {
        return 200 * (currentHeroUpgradeLevel + 1);
    }
    
    NSInteger nextUpgradePrice = [_upgradePrices[currentHeroUpgradeLevel + 1] integerValue];
    
    return nextUpgradePrice;
    
}


- (void)showButton:(UIButton *)button
{
    
    [button setEnabled:YES];
    [button setHidden:NO];
    
}


- (void)hideButton:(UIButton *)button
{
    
    [button setEnabled:NO];
    [button setHidden:YES];
    
}


- (void)decreaseUserMoney:(NSInteger)value
{
    
    // Decrease user money with the price of the Hero
    NSInteger currentUserMoney = [[NSUserDefaults standardUserDefaults] integerForKey:USER_MONEY_KEY];
    currentUserMoney -= value;
    _moneyLabel.text = [NSString stringWithFormat:@"%zd", currentUserMoney];
    
    [[NSUserDefaults standardUserDefaults] setInteger:currentUserMoney forKey:USER_MONEY_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // Decrease user money on the server
    [_communicationManager updateMyselfMoney:-value];
    
}


-(BOOL)prefersStatusBarHidden
{
    return YES;
}

@end
